import java.lang.reflect.Array;
import java.util.Arrays;

public class MArrayList implements IList{
    public int[]elem;
    public int usedsize;
    public static final int SIZE=10;

    public MArrayList() {

     this.elem=new int[SIZE];
    }
    public MArrayList(int capacity) {
        this.elem = new int[capacity];
    }

    @Override
    public void add(int data) {
         checkCapacity();
         this.elem[this.usedsize]=data;
         this.usedsize++;
    }

    @Override
    public void add(int pos, int data) {
        try {checkposOnAdd(pos);


        }catch (PosIllegality e){
            e.printStackTrace();
            return;
        }
        checkCapacity();
        for (int i = usedsize-1; i >=pos; i--) {
            elem[i+1]=elem[i];
        }
          this.elem[pos]=data;
         this.usedsize++;

    }

    @Override
    public boolean contains(int toFind) {
        if(isEmpty()) {
            return false;
        }
        for (int i = 0; i < usedsize; i++) {
            //如果是查找引用数据类型 一定记住 重写方法
            if(elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        if (isEmpty()){
            return -1;
        }
        for (int i = 0; i <usedsize; i++) {
            if (elem[i]==toFind){
            return i;
        }}
        return -1;
    }

    @Override
    public int get(int pos) {
        checkposOnAdd(pos);

        if(isEmpty()) {
            throw new MyArrayListEmpty("获取指定下标元素时" +
                    "顺序表为空！");
        }

        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        checkposOnAdd(pos);
        this.elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
int index=indexOf(toRemove);
if (index==-1){
    System.out.println("没有这个数字");
    return;
}
        for (int i = index; i <usedsize-1; i++) {
            elem[i]=elem[i+1];
        }
        usedsize--;
    }

    @Override
    public int size() {

        return this.usedsize;

    }

    @Override
    public void clear() {
        this.usedsize=0;

    }

    @Override
    public void display() {
        for (int i = 0; i <this.usedsize; i++) {
            System.out.print(this.elem[i]+"");

        }
        System.out.println();
    }

    @Override
    public boolean isFull() {

        return usedsize==elem.length;
    }

    @Override
    public boolean isEmpty() {
        return usedsize==0;
    }

    public void checkCapacity() {
        if (isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }

    }
private void checkposOnAdd(int pos)throws PosIllegality{
        if (pos<0||pos>usedsize){
            System.out.println("不合法");
            throw new PosIllegality("获取指定下标的元素异常"+pos);
        }
}


}
